package cn.bluarry.materialdesigndemo;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.List;

public class FruitAdapter extends RecyclerView.Adapter<FruitAdapter.ViewHolder> {

    private Context mcontext;
    private List<Fruit> mFruitlist;

    public FruitAdapter(List<Fruit> fruitList){
        mFruitlist=fruitList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if(mcontext==null){
            mcontext=parent.getContext();
        }
        View view= LayoutInflater.from(mcontext).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder holder=new ViewHolder(view) ;
        holder.cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int pos=holder.getAdapterPosition();
                Fruit fruit=mFruitlist.get(pos);
                Intent intent=new Intent(mcontext,FruitActivity.class);
                intent.putExtra(FruitActivity.FRUIT_NAME,fruit.getName());
                intent.putExtra(FruitActivity.FRUIT_IMAGE_ID,fruit.getId());
                mcontext.startActivity(intent);
            }
        });


        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Fruit f=mFruitlist.get(position);
        holder.fruitname.setText(f.getName());
        Glide.with(mcontext).load(f.getId()).into(holder.fruitimage);
    }

    @Override
    public int getItemCount() {
        return mFruitlist.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        CardView cardView;
        ImageView fruitimage;
        TextView fruitname;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            cardView=(CardView) itemView;
            fruitimage=itemView.findViewById(R.id.fruit_image);
            fruitname=itemView.findViewById(R.id.fruit_name);
        }
    }
}
